package com.winai.launcher.view.guide;

import android.Manifest;
import android.app.Activity;
import android.app.Dialog;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.wifi.ScanResult;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.constraintlayout.widget.ConstraintLayout;
import androidx.recyclerview.widget.LinearLayoutManager;

import com.arialyy.aria.core.Aria;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.ks.projectbasictools.base.SimpleView;
import com.ks.projectbasictools.retrofit.HttpResponseListener;
import com.ks.projectbasictools.utils.LogUtils;
import com.thanosfisherman.wifiutils.WifiUtils;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionErrorCode;
import com.thanosfisherman.wifiutils.wifiConnect.ConnectionSuccessListener;
import com.winai.launcher.R;
import com.winai.launcher.adapter.WifiItemAdapter;
import com.winai.launcher.base.BaseActivity;
import com.winai.launcher.base.db.DB_Common;
import com.winai.launcher.bean.WifiItemBean;
import com.winai.launcher.bean.requestBean.DevicePushVersionBean;
import com.winai.launcher.bean.responseEntity.DevicePushVersionEntity;
import com.winai.launcher.bean.responseEntity.GuideVideoEntity;
import com.winai.launcher.common.GlobalPublisher;
import com.winai.launcher.common.SignalSlot;
import com.winai.launcher.constant.Constant;
import com.winai.launcher.constant.DirectoryConstant;
import com.winai.launcher.constant.HttpUrls;
import com.winai.launcher.constant.LocationConstant;
import com.winai.launcher.constant.VideoConstant;
import com.winai.launcher.manager.DeviceInfoManager;
import com.winai.launcher.manager.NetworkManager;
import com.winai.launcher.manager.VideoManager;
import com.winai.launcher.manager.WifiAutoConnectManager;
import com.winai.launcher.override.ToastKs;
import com.winai.launcher.override.dialog_global.GlobalDialog;
import com.winai.launcher.service.heartBeat.HeartBeatService;
import com.winai.launcher.utils.BaseUtils;
import com.winai.launcher.utils.CollectionUtils;
import com.winai.launcher.utils.DialogUtils;
import com.winai.launcher.utils.FileUtils;
import com.winai.launcher.utils.NetworkUtils;
import com.winai.launcher.utils.NotifyReceiverUtils;
import com.winai.launcher.utils.ScreenUtils;
import com.winai.launcher.utils.ServerUtils;
import com.winai.launcher.utils.Tools;
import com.winai.launcher.utils.cache.PreloadManager;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 作者：康少
 * 时间：2020/3/13
 * 说明：配置WiFi界面
 */
public class ConfigWifiActivity extends BaseActivity {
    private Context mContext = this;

    @BindView(R.id.cl_container)
    ConstraintLayout clContainer;
    @BindView(R.id.tv_tip)
    TextView tvTip;
    @BindView(R.id.tv_next)
    TextView tvNext;
    @BindView(R.id.iv_refresh)
    ImageView ivRefresh;
    @BindView(R.id.rv_wifi)
    LRecyclerView mRecyclerView;

    private WifiManager mWifiManager;
    private WifiItemAdapter wifiAdapter;
    private Animation myAlphaAnimation;
    private WifiAutoConnectManager wifiAutoConnectManager;
    private final int RESULT_CODE = 10000;

    private GlobalDialog.Builder permissionDialog;
    private ImageView ivLoading;
    private Animation loadingAnimation;
    private Dialog loadingDialog, findNewVersionTipDialog;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_config_wifi);
        ButterKnife.bind(this);
        start();
    }

    private void start() {
        initObject();
        initListener();
        //添加数据
        if (!hasPermission(Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION)) {
            requestPermission(LocationConstant.RESULT_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
        } else {
            /*获取WiFi列表*/
            getWifiList();
        }
    }

    private void initObject() {
        /**
         * 注册网络变化监听
         */
        IntentFilter filter = new IntentFilter();
        filter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.WIFI_STATE_CHANGED_ACTION);
        filter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
        filter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);

        mWifiManager = (WifiManager) getApplicationContext().getSystemService(Context.WIFI_SERVICE);
        wifiAutoConnectManager = WifiAutoConnectManager.newInstance(mWifiManager);

        wifiAdapter = new WifiItemAdapter(mContext, "ConfigWifiActivity");
        LRecyclerViewAdapter mLRecyclerViewAdapter = new LRecyclerViewAdapter(wifiAdapter);
        mRecyclerView.setAdapter(mLRecyclerViewAdapter);
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        mRecyclerView.setPullRefreshEnabled(false);
        mRecyclerView.setLoadMoreEnabled(false);

        myAlphaAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        myAlphaAnimation.setInterpolator(new LinearInterpolator());
        BaseUtils.setTextGradient(tvNext);

        permissionDialog = new GlobalDialog.Builder(mContext)
                .setContent("请打开相关权限！")
                .setCancelText("去打开")
                .setCancelAble(false)
                .setOnCancelClickListener(new GlobalDialog.OnCancelClickListener() {
                    @Override
                    public void onClick(GlobalDialog mGlobalDialog, View v) {
                        //申请权限
                        requestPermission(LocationConstant.RESULT_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION, Manifest.permission.ACCESS_FINE_LOCATION);
                    }
                })
                .setCancelGradient(true);

        loadingAnimation = AnimationUtils.loadAnimation(mContext, R.anim.anim_loading);
        loadingAnimation.setInterpolator(new LinearInterpolator());
    }

    private void initListener() {
        GlobalPublisher.setListener(GlobalPublisher.ANY, new SignalSlot.Slot() {
            @Override
            public void onSignal(int what, int arg1, int agr2, Object argObj) {
                switch (what) {
                    case GlobalPublisher.LINK_CONFIG_WIFI:
                        //连接WiFi
                        notifyItemUI((WifiItemBean) argObj, WifiItemBean.LinkState.LINKED);
                        wifiAdapter.onTop((WifiItemBean) argObj);
                        break;
                    case GlobalPublisher.CHANGE_WIFI:
                        /*获取WiFi列表*/
                        getWifiList();
                        break;
                    case GlobalPublisher.NETWORK_AVAILABLE:
                        networkAvailable();
                        break;
                    case GlobalPublisher.NETWORK_LOST:
                        networkLost();
                        break;
                }
            }
        });
    }

    private void linkFailed(WifiItemBean mWifiItemBean, ConnectionErrorCode errorCode) {
        String msg;
        if (errorCode == ConnectionErrorCode.TIMEOUT_OCCURRED) {
            msg = "连接超时，重新尝试连接";
        } else if (errorCode == ConnectionErrorCode.DID_NOT_FIND_NETWORK_BY_SCANNING) {
            msg = "该网络不在范围内，重新尝试连接";
        } else if (errorCode == ConnectionErrorCode.AUTHENTICATION_ERROR_OCCURRED) {
            msg = "身份验证错误，重新尝试连接";
        } else {
            msg = "请检查您的网络和密码，重新尝试连接";
        }
        new GlobalDialog.Builder(mContext)
                .setTitle("网络连接失败")
                .setContent(msg)
                .setCancelText("好的")
                .setCancelAble(true)
                .setCancelGradient(true)
                .setOnCancelClickListener((mGlobalDialog, v) -> {
                    // 取消保存，忽略网络，忽略WiFi，忘记网络
                    wifiAutoConnectManager.removeWifiBySsid(mWifiItemBean.getWifiName());
                    notifyItemUI(mWifiItemBean, WifiItemBean.LinkState.UNLINK);
                }).show();
    }

    /**
     * @desc 网络连接
     */
    private void networkAvailable() {
        DB_Common dbCommon = new DB_Common(mContext);
        String isFirst = dbCommon.get("isFirstOpenApp");
        if (TextUtils.isEmpty(isFirst)) {
            checkResult(true, NetworkManager.getInstance(mContext).getConnectedWifi());
        }
    }

    /**
     * @desc 网络断开
     */
    private void networkLost() {
        notifyItemUI(NetworkManager.getInstance(mContext).getLostWifi()
                , wifiAutoConnectManager.isExsits(NetworkManager.getInstance(mContext).getLostWifi().getWifiName()) != null
                        ? WifiItemBean.LinkState.SAVED : WifiItemBean.LinkState.UNLINK);

        if (!NetworkUtils.hasNetwork(mContext))
            tvTip.setText("请先连接无线网络！");
    }

    /**
     * 说明：通知更新item的UI
     *
     * @param mLinkState 更新成哪种状态
     */
    private synchronized void notifyItemUI(WifiItemBean wifiItemBean, String mLinkState) {
        new Handler(Looper.getMainLooper()).postDelayed(new Runnable() {
            @Override
            public void run() {
                LogUtils.v("通知更新Wifi的" + wifiItemBean.getWifiName().replace("\"", "")
                        + "的UI：mLinkState = " + mLinkState);
                for (int position = 0; position < wifiAdapter.getData().size(); position++) {
                    if (wifiAdapter.getData().get(position).getWifiName().replace("\"", "")
                            .equals(wifiItemBean.getWifiName().replace("\"", ""))) {
                        wifiAdapter.getData().get(position).setLinkStatus(mLinkState);
                        wifiAdapter.notifyItemChanged(position);
                        break;
                    }
                }
                if (mLinkState.equals(WifiItemBean.LinkState.SAVED) || mLinkState.equals(WifiItemBean.LinkState.LINKING)) {
                    //置顶
                    wifiAdapter.onTop(wifiItemBean);
                    mRecyclerView.scrollToPosition(0);
                }
            }
        }, 1000);
    }

    private void checkResult(boolean isSuccess, WifiItemBean wifiItemBean) {
        if (isSuccess) {
            LogUtils.i("Wifi：Wifi连接成功！");
            notifyItemUI(wifiItemBean, WifiItemBean.LinkState.LINKED);
            tvTip.setText("配网成功！");
            //切换网络后上报服务器
            DeviceInfoManager.getInstance(mContext).updateWifiInfo();
            //开始预加载引导视频
            ServerUtils.requestJsonPost(HttpUrls.GUIDE_VIDEO, null, new Object(), new HttpResponseListener<GuideVideoEntity>() {
                @Override
                public void onResponse(GuideVideoEntity var1, boolean isCache) {
                    if (var1 != null && var1.getData() != null && var1.getData().getVideoPath() != null) {
                        VideoConstant.URL_AD = var1.getData().getVideoPath();
                        PreloadManager.getInstance(mContext).addPreloadTask(var1.getData().getVideoPath(), 0);
                    }
                    //检查更新
                    checkVersion();
                }
            });
            //联网成功后 限制不能点击item
//            wifiAdapter.setItemClickListener(null);
        } else {
            LogUtils.i("Wifi：Wifi连接失败！");
            notifyItemUI(wifiItemBean, WifiItemBean.LinkState.UNLINK);
        }
        /*获取WiFi列表*/
        getWifiList();
    }

    private long startTime = 0;

    /**
     * 说明：获取WiFi列表
     */
    private boolean getWifiList() {
        long ct = System.currentTimeMillis();
        if (ct - startTime < 5000) {
            LogUtils.e("5s内限制Wifi重复扫描");
            return false;
        }
        startTime = ct;
        runOnUiThread(new Runnable() {
            @Override
            public void run() {
                ivRefresh.startAnimation(myAlphaAnimation);
                WifiUtils.withContext(mContext).enableWifi();
                WifiUtils.withContext(getApplicationContext()).scanWifi(this::getScanResults).start();
            }

            private void getScanResults(@NonNull final List<ScanResult> results) {
                List<ScanResult> resultList = WifiAutoConnectManager.noSameName(results);//去除重名wifi
                if (!CollectionUtils.isNullOrEmpty(resultList)) {
                } else {
                    LogUtils.i("Wifi：扫描WiFi列表：没有找到Wifi");
                    mRecyclerView.refreshComplete(0);
                }
                refreshData(resultList);
            }
        });
        return true;
    }

    /**
     * 说明：刷新WiFi列表数据
     */
    private void refreshData(List<ScanResult> scanResults) {
        new Handler(Looper.getMainLooper()).post(new Runnable() {
            @Override
            public void run() {
                if (!CollectionUtils.isNullOrEmpty(scanResults)) {
                    List<WifiItemBean> wifiList = new ArrayList<>();//未连接WiFi列表
                    for (ScanResult scanResult : scanResults) {
                        if (NetworkManager.getInstance(mContext).getConnectedWifi() != null
                                && scanResult.SSID.equals(NetworkManager.getInstance(mContext).getConnectedWifi().getWifiName())) {
                            wifiList.add(new WifiItemBean(
                                    scanResult.SSID
                                    , scanResult.BSSID
                                    , WifiItemBean.LinkState.LINKED
                                    , scanResult.capabilities
                                    , scanResult.level
                            ));
                        } else {
                            wifiList.add(new WifiItemBean(
                                    scanResult.SSID
                                    , scanResult.BSSID
                                    , wifiAutoConnectManager.isExsits(scanResult.SSID) != null
                                    ? WifiItemBean.LinkState.SAVED : WifiItemBean.LinkState.UNLINK
                                    , scanResult.capabilities
                                    , scanResult.level
                            ));
                        }
                    }
                    wifiAdapter.refreshData(wifiList);
                    mRecyclerView.refreshComplete(scanResults.size());
                    if (NetworkManager.getInstance(mContext).getConnectedWifi() != null) {
                        wifiAdapter.onTop(NetworkManager.getInstance(mContext).getConnectedWifi());
                    }
                } else {
                    mRecyclerView.refreshComplete(0);
                }
                ivRefresh.clearAnimation();
            }
        });
    }

    private void checkVersion() {
        showLoading();
        DevicePushVersionBean mDevicePushVersionBean = new DevicePushVersionBean();
//        mDevicePushVersionBean.setName("X106F-DEV-B1.0.1-Provision-20210225-09:51");
        mDevicePushVersionBean.setName(BaseUtils.getSystemVersion());
        mDevicePushVersionBean.setEquipmentId(BaseUtils.getDeviceId());
        ServerUtils.requestJsonPost(HttpUrls.CHECK_VERSION, null, mDevicePushVersionBean
                , new HttpResponseListener<DevicePushVersionEntity>() {
                    @Override
                    public void onResponse(DevicePushVersionEntity var1, boolean isCache) {
                        runOnUiThread(new Runnable() {
                            @Override
                            public void run() {
                                dismissLoadingDialog();
                                if (isCache) {
                                    return;
                                }
                                if (var1.getData() != null) {
                                    //有更新
                                    LogUtils.i("发现ROM新版本");
                                    boolean mandatory = var1.getData().isMandatory();//true：强制更新；false：非强制更新
                                    HeartBeatService.md5 = var1.getData().getMd5();
                                    showFindNewVersionDialog(var1.getData().getVersionName(), var1.getData().getPath());
//                                    UpgradeProgressManager.getInstance(mContext).setVersionName(var1.getData().getVersionName());
//                                    UpgradeWindowManager.getInstance(mContext, var1.getData().getPath()).showTip();
                                } else {
                                    LogUtils.i("无ROM更新");
                                    gotoNext();
                                }
                            }
                        });
                    }

                    @Override
                    public void onError(int code, String msg) {
                        super.onError(code, msg);
                        dismissLoadingDialog();
                    }
                });
    }

    /**
     * @date 4/20/21
     * @desc 发现新版本——提示
     */
    private void showFindNewVersionDialog(String versionName, String path) {
        //禁止唤醒
        NotifyReceiverUtils.notifyToggleWakeUpReceiver(mContext, false);
        //禁止下拉
        NotifyReceiverUtils.notifyPulldownReceiver(mContext, false);
        //通知QQ音乐暂停
        NotifyReceiverUtils.notifyControlQQMusic(mContext, Constant.MediaControllerStop, null);
        //关闭曲艺
        VideoManager.getInstance(mContext).stop(true);

        SimpleView view = new SimpleView(mContext, R.layout.dialog_find_new_version);
        initFindNewVersionTipView(view, versionName, path);
        findNewVersionTipDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), false);
        Tools.showDialog(findNewVersionTipDialog);
    }

    private void initFindNewVersionTipView(SimpleView view, String versionName, String mPath) {
        TextView tvVersoin = view.findViewById(R.id.tv_version);
        tvVersoin.setText(versionName);
        view.findViewById(R.id.tv_update).setOnClickListener(v -> {
            if (mPath == null) {
                ToastKs.show(mContext, "更新文件为空，请联系后台管理员");
                return;
            }
            boolean fileExists = FileUtils.isFileExists(new File(FileUtils.getLocalPath(mPath)));
            LogUtils.d("系统更新文件是否存在 fileExists = " + fileExists);
            if (!fileExists) {
                downloadFile(mPath);
            } else {
                GlobalPublisher.Notify(GlobalPublisher.DOWNLOAD_ROM_COMPLETE, mPath);
            }
            hideFindNewVersionTip();
        });
    }

    private void downloadFile(String path) {
        /**文件数量大于两个时，删除文件夹下所有内容*/
        List<File> fileList = FileUtils.getFile(new File(DirectoryConstant.ROM_PATH));
        if (fileList != null && fileList.size() > 2) {
            FileUtils.deleteFiles(DirectoryConstant.ROM_PATH);
        }
        long taskId = Aria.download(this)
                .load(path)     //读取下载地址
                .setFilePath(FileUtils.getLocalPath(path)) //设置文件保存的完整路径
                .ignoreFilePathOccupy()
                .create();   //创建并启动下载
    }

    private void hideFindNewVersionTip() {
        Tools.dimssDialog(findNewVersionTipDialog);
    }

//    /**
//     * @date 3/16/21
//     * @desc 当前已是最新版本——提示
//     */
//    private void showNewestVersionTip() {
//        SimpleView view = new SimpleView(mContext, R.layout.dialog_newest_version);
//        initNewestTipView(view);
//        newestVersionTipDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), true);
//        Tools.showDialog(newestVersionTipDialog);
//    }
//
//    private void initNewestTipView(SimpleView view) {
//        view.findViewById(R.id.iv_close).setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                hideNewestVersionTip();
//            }
//        });
//    }
//
//    private void hideNewestVersionTip() {
//        Tools.dimssDialog(newestVersionTipDialog);
//    }

    /**
     * @date 3/16/21
     * @desc 正在检查更新——loading
     */
    private void showLoading() {
        SimpleView view = new SimpleView(mContext, R.layout.dialog_upgrade_loading);
        initView(view);
        loadingDialog = DialogUtils.dialogCenter(mContext, view, ScreenUtils.dip2px(mContext, 380), false);
        Tools.showDialog(loadingDialog);
    }

    private void initView(SimpleView view) {
        ivLoading = view.findViewById(R.id.iv_loading);
        runOnUiThread(() -> {
            ivLoading.setVisibility(View.VISIBLE);
            ivLoading.startAnimation(loadingAnimation);
        });
    }

    private void dismissLoadingDialog() {
        Tools.dimssDialog(loadingDialog);
        runOnUiThread(() -> {
            ivLoading.setVisibility(View.GONE);
            ivLoading.clearAnimation();
        });
    }

    private long startTimeConnecting = 0;//正在连接——单位时间内限制访问次数

    /**
     * 作者：康少
     * 时间：2020/3/24 0024
     * 说明：监听网络变化
     */
    public class WifiReceiver extends BroadcastReceiver {
        public final String TAG = "zhxk_WifiReceiver";

        @Override
        public void onReceive(Context context, Intent intent) {
            if (intent == null) {
                return;
            }
            switch (intent.getAction()) {
                case WifiManager.NETWORK_STATE_CHANGED_ACTION:
                    /**
                     * 在收到action 为WifiManager.NETWORK_STATE_CHANGED_ACTION的广播时,
                     * 以下三个方法能够获取手机当前连接的Wifi信息
                     * 注意在wifi断开时Intent中不包含WifiInfo对象，却包含bssid
                     */
                    NetworkInfo networkInfo = intent.getParcelableExtra(WifiManager.EXTRA_NETWORK_INFO);
                    if (networkInfo == null) {
                        return;
                    }
                    String SSID = networkInfo.getExtraInfo();
                    SSID = SSID.replace("\"", "");
                    if (TextUtils.isEmpty(SSID) || SSID.contains("<unknown ssid>")) {
                        return;
                    }
                    if (networkInfo.getState().equals(NetworkInfo.State.CONNECTING)) {
                        if (filterConnecting()) return;
                        Log.i(TAG, "wifi正在连接 SSID = " + SSID);
                        WifiItemBean bean = new WifiItemBean();
                        //获取当前wifi名称
                        bean.setWifiName(SSID);
                        bean.setLinkStatus(WifiItemBean.LinkState.LINKING);
                        notifyItemUI(bean, WifiItemBean.LinkState.LINKING);
                    }
                    break;
            }
        }

        /**
         * 说明：限制1.5s内执行WiFi断开逻辑
         */
        private boolean filterConnecting() {
            long ct = System.currentTimeMillis();
            if (ct - startTimeConnecting < 1500) {
                Log.e(TAG, "1.5s内限制wifi正在连接访问");
                return true;
            }
            startTimeConnecting = ct;
            return false;
        }
    }

    @OnClick({R.id.tv_next, R.id.cl_refresh})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_next:
                gotoNext();
                break;
            case R.id.cl_refresh:
                ivRefresh.startAnimation(myAlphaAnimation);
                /*获取WiFi列表*/
                getWifiList();
                break;
        }
    }

    private void gotoNext() {
        if (NetworkUtils.hasNetwork(mContext)) {
            /* 跳转客户的激活app */
            try {
                Intent intent = new Intent();
                intent.setClassName("com.aiyisheng.speaker"
                        , "com.aiyisheng.speaker.user.activation.ActivationActivity");
                LogUtils.i("BaseUtils.getDeviceId() = " + BaseUtils.getDeviceId());
                intent.putExtra("deviceId", BaseUtils.getDeviceId());//新增deviceId参数
                startActivityForResult(intent, RESULT_CODE);
            } catch (Exception e) {
                e.printStackTrace();
                ToastKs.show(mContext, "您还没有安装小艾音箱");
            }
        } else {
            tvTip.setText("请先连接无线网络！");
        }
    }

    /**
     * 说明：勿删！！
     *
     * @return true 放开上滑返回手势，默认true
     */
    public boolean isAllowCustomSliding() {
        return false;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        LogUtils.d("配网onActivityResult，data = " + data + ",resultCode= " + resultCode
                + ",requestCode == RESULT_CODE: " + (requestCode == RESULT_CODE));
        if (resultCode == Activity.RESULT_OK) {
            if (requestCode == RESULT_CODE) {
                if (data != null) {
                    long userId = data.getLongExtra("userId", 0);
                    //进入引导视频
                    Intent intent = new Intent(mContext, GuideVideoActivity.class);
                    startActivity(intent);
                    // 更新设备激活状态
                    DeviceInfoManager.getInstance(mContext).firstBindAndActivate(
                            true
                            , BaseUtils.timeStamp2Date(BaseUtils.getInitTime(), "")
                            , true
                            , String.valueOf(userId)
                    );
                } else {
                    LogUtils.d("配网onActivityResult，data = null");
                    //进入引导视频
                    Intent intent = new Intent(ConfigWifiActivity.this, GuideVideoActivity.class);
                    startActivity(intent);
                }
            } else if (requestCode == Constant.RESULT_LINK_WIFI) {
                if (data != null) {
                    WifiItemBean wifiItemBean = data.getParcelableExtra("wifiItemBean");
                    LogUtils.d("返回的wifiItemBean对象 = " + wifiItemBean);
                    if (wifiItemBean != null) {
                        //连接中…
                        notifyItemUI(wifiItemBean, WifiItemBean.LinkState.LINKING);
                        // 连接wifi
                        WifiUtils.withContext(mContext)
                                .connectWith(wifiItemBean.getWifiName(), wifiItemBean.getBSSID(), "")
                                .setTimeout(15000)
                                .onConnectionResult(new ConnectionSuccessListener() {
                                    @Override
                                    public void success() {
                                        notifyItemUI(wifiItemBean, WifiItemBean.LinkState.LINKED);
                                    }

                                    @Override
                                    public void failed(@NonNull ConnectionErrorCode errorCode) {
                                        linkFailed(wifiItemBean, errorCode);
                                    }
                                })
                                .start();
                    }
                }
            }
        } else {
            ToastKs.show(ConfigWifiActivity.this, "配网成功");
            //进入引导视频
            Intent intent = new Intent(ConfigWifiActivity.this, GuideVideoActivity.class);
            startActivity(intent);
        }
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (requestCode == LocationConstant.RESULT_LOCATION) {
            if (grantResults.length > 0) {
                if (grantResults[0] == PackageManager.PERMISSION_GRANTED) {
                    // 第一次获取到权限，请求定位
                    /*获取WiFi列表*/
                    getWifiList();
                } else {
                    // 没有获取到权限，做特殊处理
                    if (permissionDialog != null) {
                        permissionDialog.show();
                    }
                }
            } else {
                // 没有获取到权限，做特殊处理
                if (permissionDialog != null) {
                    permissionDialog.show();
                }
            }
        }
    }
}
